package com.dwjm.goods;

import com.dwjm.CommonResult;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/allGoods")
public class AllGoodsHandler extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        // 默认页码和每页的大小
        int ipage = 1;
        int isize = 3;

        try {
            String page = req.getParameter("page");
            String size = req.getParameter("size");
            if (page != null) ipage = Integer.parseInt(page);
            if (size != null) isize = Integer.parseInt(size);
        } catch (NumberFormatException e) {
            // 参数格式错误，返回错误信息
            CommonResult<String> error = CommonResult.fail(400, "分页参数格式错误");
            resp.getWriter().write(new Gson().toJson(error));
            return;
        }

        GoodDao goodDao = new GoodDaolpml();
        List<Goods> allGoods = goodDao.findAllGoods(ipage, isize);

        Gson gson = new Gson();
        CommonResult<?> result;

        if (allGoods != null && !allGoods.isEmpty()) {
            result = CommonResult.success(allGoods);
        } else {
            result = CommonResult.fail(500, "没有对应的数据");
        }

        String json = gson.toJson(result);
        System.out.println(json); // 调试打印
        resp.getWriter().write(json);
    }

}
